//
//  UploadImage.m
//  QiXing
//
//  Created by 零零壹 on 2017/2/20.
//  Copyright © 2017年 梁晨. All rights reserved.
//

#import "UploadImage.h"
#define kTIMEOUT 20

@implementation UploadImage
+(instancetype)sharedClient
{
    static UploadImage *apiClient = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate,^{
        apiClient = [[self alloc] init];
    });
    return apiClient;
}

-(void)doUploadImage:(NSString *)methodString parameters:(id)parameters image:(UIImage*)image successBlock:(SuccessBlock)success failureBlock:(FailureBlock)failure
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:[NSString stringWithFormat:@"%@%@",KUrl,methodString] parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData)
     {
         if (image)
         {
//             NSData *imageData = UIImageJPEGRepresentation([self compressImage:image newWidth:KscreenW/3], 1);
             NSData *imageData = [self compressImage:image];
             [formData appendPartWithFileData:imageData name:@"key1" fileName:@"key2" mimeType:@"image/jpeg"];
             //             if ([UIImageJPEGRepresentation(image, 1)length]>20000) {
//                 [formData appendPartWithFileData:UIImageJPEGRepresentation(image, 0.5) name:@"key1" fileName:@"key2" mimeType:@"image/jpeg"];
//             }else
//             {
//                 [formData appendPartWithFileData:UIImageJPEGRepresentation(image, 1) name:@"key1" fileName:@"key2" mimeType:@"image/jpeg"];
//             }
         }
     } progress:^(NSProgress * _Nonnull uploadProgress)
     {
     } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
         success(responseObject);
     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         failure(error.description);
     }];
}

-(UIImage *)compressImage:(UIImage *)image newWidth:(CGFloat)newImageWidth
{
    if (!image) return nil;
    float imageWidth = image.size.width;
    float imageHeight = image.size.height;
    float width = newImageWidth;
    float height = image.size.height/(image.size.width/width);

    float widthScale = imageWidth /width;
    float heightScale = imageHeight /height;

    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(CGSizeMake(width, height));

    if (widthScale > heightScale) {
        [image drawInRect:CGRectMake(0, 0, imageWidth /heightScale , height)];
    }
    else {
        [image drawInRect:CGRectMake(0, 0, width , imageHeight /widthScale)];
    }

    // 从当前context中创建一个改变大小后的图片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();

    return newImage;

}



- (NSData *)compressImage:(UIImage *)image
{
    CGSize size = [self scaleSize:image.size];
    UIGraphicsBeginImageContext(size);
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage * scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    NSUInteger maxFileSize = 1024 * 1024;
    CGFloat compressionRatio = 1;
    CGFloat maxCompressionRatio = 0.1f;

    NSData *imageData = UIImageJPEGRepresentation(scaledImage, compressionRatio);

    while (imageData.length > maxFileSize && compressionRatio > maxCompressionRatio) {
        compressionRatio -= 0.1f;
        imageData = UIImageJPEGRepresentation(image, compressionRatio);
    }

    return imageData;
}



- (CGSize)scaleSize:(CGSize)sourceSize
{
    float width = sourceSize.width;
    float height = sourceSize.height;

    if (width >= height) {
        return CGSizeMake(800, 800 * height / width);
    } else {
        return CGSizeMake(800 * width / height, 800);
    }
}


@end
